#!/usr/bin/env python
from __future__ import absolute_import
import os
import shutil
import unittest
import tempfile
import forest.api
from forest.api import get_tool
from forest.tool import search_tools
from forest.testing import mock_tree_file
from forest.config import Config
from forest.command import search_commands
from forest.plugins import registry
from forest.registry import TOOLS_REGISTRY_PREFIX

class MockTreeTestCase(unittest.TestCase):
    ''' This is a testcase loging a single string, self.tree as a config file.

        It creates a temporary install and build root.
    '''
    tree = None
    def setUp(self):
        search_tools()
        self.tree_file = mock_tree_file(self.tree)
        self.config = Config()
        self.config.load_file(self.tree_file)
        self.install_root = tempfile.mkdtemp()
        self.build_root = tempfile.mkdtemp()
        self.config.set_install_root(self.install_root)
        self.config['build_root']= self.build_root
        search_commands()

    def tearDown(self):
        os.unlink(self.tree_file)
        shutil.rmtree(self.install_root)
        shutil.rmtree(self.build_root)


class MockToolsAndTreeTestCase(unittest.TestCase):
    ''' Tis is a test case for highly destructive commands.
    '''

    tools_to_mock = [
    'system.poll',
    'system.execute',
    'system.mount',
    'system.bindmount',
    'system.format',
    'system.chroot',
    'parted.probe',
    'udev.settle'
    ]

    tree = None

    def setUp(self):
        search_tools()
        self.tree_file = mock_tree_file(self.tree)
        self.config = Config()
        self.config.load_file(self.tree_file)
        self.install_root = tempfile.mkdtemp()
        self.build_root = tempfile.mkdtemp()
        self.config.set_install_root(self.install_root)
        self.config['build_root'] = self.build_root
        self.config.set_dry_run(True)

        RUN_SEQUENCE = self.run_sequence = []

        # mock out certain destructive tools
        for tool in self.tools_to_mock:
            registry.register(TOOLS_REGISTRY_PREFIX+tool, self.dry_get_tool(tool))

        search_commands()

    def tearDown(self):
        os.unlink(self.tree_file)
        shutil.rmtree(self.install_root)
        shutil.rmtree(self.build_root)

    def replace_get_tool_with_fake(self):
        forest.api.get_tool = self.dry_get_tool

    def dry_get_tool(self, toolname):
        RUN_SEQUENCE = self.run_sequence

        class fake_tool(list):
            def __init__(self, *args, **kwargs):
                print 'DRY RUN', toolname, args, kwargs
                RUN_SEQUENCE.append((toolname, args))
                self.toolname = toolname

            def __enter__(self):
                print 'DRY RUN: ENTER', self.toolname
                return self


            def __exit__(self, type, value, traceback):
                print 'DRY RUN: EXIT', self.toolname

        return fake_tool
